from datetime import datetime
from io import BytesIO
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
import redis
import os
import tempfile
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from doc_service.utils import merge_pdfs
from reportservice.helpers import ApiResponse
import json
from yida_app_service.utils.xmutils import convert_to_pdf
from yida_app_service.views import get_xm_client
from yida_app_service.xu_cloud_client import XmCloudBaseClient
from yida_app_service.haorui.xm_cloud_config import XmCloudClient
from .yida_config import YidaClient
import requests
from oss_service.views import bucket
import pandas as pd
from io import BytesIO
import uuid
import base64
import qrcode
from dateutil import parser

yida_client = YidaClient()
admin_user_id = "014835331124251186"
r = redis.StrictRedis(host='10.8.0.83', port=6379, db=0)
company_name = "haorui"


@csrf_exempt
@require_http_methods(["GET"])
def prepare_price_shell(request):
    project_id = request.GET.get('project_id')
    project_info = yida_client.get_form_items_by_ids("FORM-B973E0A2EA7C452F9D3B7077821CE7C6TVSO",
                                      project_id,
                                      admin_user_id)
    if(project_info and project_info[0].form_data.get('attachmentField_lvhny282')):
        attachment = json.loads(project_info[0].form_data['attachmentField_lvhny282'])
        if(attachment):
            download_url = attachment[0].get("downloadUrl")
        else:
            return ApiResponse.fail("未找到价格清单")
        full_download_url = yida_client.get_full_download_url(admin_user_id, download_url)
        response = requests.get(full_download_url.body.result)
        if response.status_code == 200:
            price_shell_content = response.content
            excel_file = BytesIO(price_shell_content)
            df = pd.read_excel(excel_file)
            for index, row in df.iterrows():
                redis_key = f"{str(row['检测项目'])}-{str(row['检测参数'])}"
                redis_value = str(row['费用'])
                # 存储到Redis
                r.set(f"haorui:{project_id}:{redis_key}", redis_value)
            return ApiResponse.success("success")
        else:
            return ApiResponse.fail("fail")
    else:
        return ApiResponse.fail("未找到价格清单")


@csrf_exempt
@require_http_methods(["GET"])
def get_single_price(request):
    project_id = request.GET.get('project_id')
    param_name = request.GET.get('param_name')
    param_key = rf"haorui:{project_id}:{param_name}"
    price = r.get(param_key)
    if price:
        price = int(price.decode())
        return ApiResponse.success(price)
    else:
        return ApiResponse.fail("未找到价格")


@csrf_exempt
@require_http_methods(["POST"])
def gen_total_price(request):
    datasource: dict[str, any] = json.loads(request.body)
    project_id = datasource["project_id"]
    param_names = datasource['param_names']
    res_price = 0
    for param_name in param_names:
        param_key = rf"shujian:{project_id}:{param_name}"
        price = r.get(param_key)
        if price:
            price = int(price.decode())
            res_price = res_price + price
        else:
            ApiResponse.fail("未找到价格")
    return ApiResponse.success(res_price)


@csrf_exempt
@require_http_methods(["POST"])
def batch_print_report_statement(request):
    req_data = json.loads(request.body)
    form_inst_ids = req_data.get('form_inst_ids',[])
    form_uuid = "FORM-9C48925B91404850BB1D00FC021A33C5RM1O"
    model_id = 159
    table_data = []
    render_data = {
        "结算数据":table_data
    }

    for form_inst_id in form_inst_ids:
        yida_instance = yida_client.get_form_items_by_ids(form_uuid,form_inst_id,admin_user_id)
        form_data:dict = yida_instance[0].form_data
        
        bg_info_str=form_data.get('associationFormField_lvw1b8w6_id')
        bg_info_detail=yida_client.get_associated_form_data(bg_info_str, admin_user_id)
        report_date_timestamp = bg_info_detail.get('dateField_lvhpww4i') #报告日期的毫秒时间戳
        if report_date_timestamp is not None:
            report_date = datetime.fromtimestamp(report_date_timestamp / 1000).strftime('%Y年%m月%d日')
        else:
            report_date = ''  # 报告日期

        wt_info_str = form_data.get('associationFormField_lvvrg0yz_id')
        wt_info_detail = yida_client.get_associated_form_data(wt_info_str, admin_user_id)
        project_name = wt_info_detail.get('textField_lvhw5i6u') #工程名称
        gc_info_str = wt_info_detail.get('associationFormField_lvhvyzpu_id') #关联工程
        gc_info_detail = yida_client.get_associated_form_data(gc_info_str, admin_user_id)
        entrust_unit = gc_info_detail.get('textField_lvhea612') #委托单位

        test_items = []  # 使用列表来收集参数
        test_project = wt_info_detail.get('selectField_lvhhb44k')  #检测项目
        if(wt_info_detail.get('radioField_lw8xidqm')=='常规'):
            test_parms_table = wt_info_detail.get('tableField_lvituc5q')
            unit = test_parms_table[0].get('selectField_lvj4hiij')  # 单位
    
            for test_parm in test_parms_table:
                item = test_parm.get('selectField_lwik49tr')
                if item:  
                    test_items.append(item)
    
            test_items = '、'.join(test_items)

        count =1 #数量
        report_info_str = form_data.get('associationFormField_lvw1b8w6_id')
        report_info_detail = yida_client.get_associated_form_data(report_info_str, admin_user_id)
        report_number = report_info_detail.get('textField_lvksipo5') #报告编号
        unit_price = float(wt_info_detail.get('numberField_lvkpm5tz')) #单价
        total_price = unit_price  #检测费
        table_data.append([report_date,entrust_unit,project_name,test_project,test_items,unit,count,report_number,unit_price,total_price])
    
    XmCloudClient = get_xm_client(company_name)
    xm_client:XmCloudBaseClient = XmCloudClient()
    result_render = xm_client.render_model_xlsx(model_id,render_data)
    if result_render.get("code") == 200:
        res_data = result_render.get("data")
        result_url =xm_client.gen_detection_record_url(res_data.get("id"))
        if result_url.get("code") == 200:
            res = result_url.get("data")
            return ApiResponse.success(res.get("preview_url"))



@csrf_exempt
@require_http_methods(["GET"])
def get_full_report(request):
    form_uuid = "FORM-C1A327686C7A4FC68273017159DDE1A9PWVO"
    form_inst_id = request.GET.get('formInstId')
    model_id = request.GET.get('model_id')
    # 获取表单数据
    yida_instance = yida_client.get_form_items_by_ids(form_uuid, form_inst_id, admin_user_id)
    if not yida_instance:
        return ApiResponse.fail(message="未找到相关表单数据")
    
    form_data:dict = yida_instance[0].form_data

    # 获取封面数据
    render_data = get_render_data(form_data)

    # 调用渲染服务
    XmCloudClient = get_xm_client(company_name)
    xm_client:XmCloudBaseClient = XmCloudClient()
    result = xm_client.render_model(model_id,render_data)

    if result.get("code") != 200:
        return ApiResponse.fail(message="封面渲染失败")

    # 获取封面下载URL
    res_data = result.get("data")
    url_res = xm_client.gen_detection_record_url(res_data.get("id"))

    if url_res.get("code") != 200:
        return ApiResponse.fail(message="未找到报告生成记录")
    
    yida_client.update_form_data_by_id(form_uuid,admin_user_id,form_inst_id,{
    "attachmentField_lwed3j50":[
        {
        "downloadUrl": url_res.get("data").get("download_url"),
        "name": "报告封面.docx",
        "previewUrl": url_res.get("data").get("preview_url"),
        "url": url_res.get("data").get("preview_url"),
        "ext": "docx"
        }
    ]})
    # 获取封面和内容文件URL
    cover_url = url_res.get("data").get("download_url")
    form_data:dict = yida_instance[0].form_data
    content_info = json.loads(form_data["attachmentField_lvhrt9vg"])[0]
    content_url = content_info.get("downloadUrl")
    content_name = content_info.get("name")

    full_download_url = yida_client.get_full_download_url(admin_user_id,content_url)

    # 下载和转换PDF
    temp_dir = tempfile.mkdtemp()
    convert_and_download(cover_url, temp_dir, "cover.pdf")
    #内容文件下载
    response = requests.get(full_download_url.body.result)
    ext = content_name.split(".")[-1]
    if response.status_code == 200:
        content_content = response.content
        temp_content_path = os.path.join(temp_dir, f"content.{ext}")
        print(f"内容文件已存入缓存文件：{temp_content_path}")
        with open(temp_content_path, 'wb') as temp_file:
            temp_file.write(content_content)
        if ext == "xlsx" or ext == "docx":
            convert_to_pdf(temp_content_path,temp_dir)
            temp_content_path = os.path.join(temp_dir, f"content.pdf")

    # 构建PDF文件的路径
    cover_pdf = os.path.join(temp_dir, f"cover.pdf")
    content_pdf = os.path.join(temp_dir, f"content.pdf")
    # 合并PDF
    out_path = os.path.join(temp_dir, f"whole.pdf")
    merge_pdfs([cover_pdf, content_pdf], out_path)

    # 上传PDF到OSS
    oss_pdf_key = f"yida-app/{company_name}/{form_uuid}/{form_inst_id}/完整报告.pdf"
    bucket.put_object_from_file(oss_pdf_key, out_path)
    out_url = f"https://api.zjcxjc.cn/api/v1/yida-app/common/download_file/{oss_pdf_key}"

    # 更新宜搭表单
    update_yida_full_report(form_uuid,form_inst_id,out_url,oss_pdf_key)

    return ApiResponse.success(message='成功获取完整报告',data=out_url)

def update_yida_full_report(form_uuid,form_inst_id,out_url,oss_key):
    '''更新宜搭的完整报告附件的组件'''

    yida_client.update_form_data_by_id(form_uuid, admin_user_id, form_inst_id, {
    "attachmentField_lwf41dza": [{
        "downloadUrl": out_url,
        "name": "完整报告.pdf",
        "previewUrl": out_url,
        "url": out_url,
        "oss_key":oss_key,
        "ext": "pdf"
    }],
    "textField_lwrvb5wq":oss_key
})

def get_render_data(form_data):
    '''准备封面数据'''
    report_number = form_data.get('textField_lvksipo5') #报告编号
    wt_info_str = form_data.get('associationFormField_lvj6iq1p_id')
    wt_info_detail = yida_client.get_associated_form_data(wt_info_str,admin_user_id)
    test_item = wt_info_detail.get('selectField_lvhhb44k') #检测项目
    gc_info_str = wt_info_detail.get('associationFormField_lvhvyzpu_id')
    gc_info_detail = yida_client.get_associated_form_data(gc_info_str,admin_user_id)
    entrust_unit = gc_info_detail.get('textField_lvhea612')#委托单位
    contract_id = gc_info_detail.get('textField_lvhea60s') #合同编号
    project_name = wt_info_detail.get('textField_lvhw5i6u')#工程名称
    test_category = wt_info_detail.get('selectField_lvhg6k0l') #检测类别
    example_id = wt_info_detail.get('textField_lvhpww3f')
    js_unit = entrust_unit #建设单位
    jl_unit = gc_info_detail.get('textField_lvhea62s') #监理单位
    sg_unit = gc_info_detail.get('textField_lvhea628') #施工单位
    project_bw = gc_info_detail.get('textField_lwj204x0') #工程部位/规格型号
    design_unit = gc_info_detail.get('textField_lwk4ncbp') #设计单位
    project_addr = gc_info_detail.get('selectField_lvhea61j')#工程地址
    jzr_name = gc_info_detail.get('textField_lvhea62z')#见证人
    entrust_date_stmap = wt_info_detail.get('dateField_lw4oxok2') #受理日期
    date_range = form_data.get('cascadeDateField_lvhpww4h')
    if date_range: 
        jc_date_stamp = int(date_range[0]) #检测日期

    jc_category = wt_info_detail.get('radioField_lw8xidqm')
    test_items = []  # 检测参数：数量
    test_standards=[]
    if(jc_category=='常规'):
        test_parms_table = wt_info_detail.get('tableField_lvituc5q')
        for test_parm in test_parms_table:
            item = test_parm.get("selectField_lvituc5r","")+":"+str(test_parm.get('numberField_lvituc5s',0))
            standard = test_parm.get('textField_lx9ssfuj','') 
            if item:  
                test_items.append(item)
                test_standards.append(standard)
    elif(jc_category=='地基'):
        test_parms_table = wt_info_detail.get('tableField_lw8n0thp')
        for test_parm in test_parms_table:
            item = test_parm.get('selectField_lw8n0thk') + ":"+ str(test_parm.get('numberField_lw8n0thl'))
            standard = test_parm.get('textField_lx9ssful','') 
            if item:  
                test_items.append(item)
                test_standards.append(standard)
    elif(jc_category=='结构实体'):
        test_parms_table = wt_info_detail.get('tableField_lw8xidr2')
        for test_parm in test_parms_table:
            item = test_parm.get('selectField_lw8xidqx') +":"+ str(test_parm.get('numberField_lw8xidqy'))
            standard = test_parm.get('textField_lx9ssfun','')
            if item:  
                test_items.append(item)
                test_standards.append(standard)

    test_items = '、'.join(test_items)        
    test_standards = '、'.join(test_standards)  #检测标准
    example_name = wt_info_detail.get('textareaField_lvhpww36') #样品名称
    jcr_sign_url = form_data.get('digitalSignatureField_lwed3j4v') #检测人签名1
    shr_sign_url = form_data.get('digitalSignatureField_lwinoatx') #审核人签名
    pzr_sign_url = form_data.get('digitalSignatureField_lwinoaty') #批准人签名
    pzr_name = form_data.get('selectField_lwkc2qg8') #批准人名字
    shr_name = form_data.get('selectField_lwkc2qg7') #审核人名字
    ass_jcr :list = json.loads(json.loads(form_data.get('associationFormField_lwu19i9t_id')))
    titles = [obj['title'] for obj in ass_jcr] #检测人名字
    jcr_names = '、'.join(titles) #检测人名字
    qf_date = datetime.now().timestamp() #签发日期
    render_data = {
    "报告编号": report_number,
    "样品编号":example_id,
    "检测项目": test_item,
    "项目名称":test_item,
    "工程名称": project_name,
    "委托单位": entrust_unit,
    "合同编号": contract_id,
    "检测类别": test_category,
    "建设单位": js_unit,
    "监理单位": jl_unit,
    "施工单位": sg_unit,
    "规格型号": project_bw,
    "设计单位": design_unit,
    "工程地址": project_addr,
    "见证人": jzr_name,
    "受理日期": entrust_date_stmap,
    "检测日期": jc_date_stamp,
    "检测参数及数量": test_items,
    "样品名称": example_name,
    #"审核人签名": shr_sign_url,
   # "批准人签名": pzr_sign_url,
    #"检测人签名1": jcr_sign_url,
    "批准人": pzr_name,
    "审核人": shr_name,
    "检测人1": jcr_names,
    "签发日期":qf_date,
    "检测依据":test_standards
    }
    return render_data


def convert_and_download(url, output_dir, filename):
    response = requests.get(url)
    if response.status_code == 200:
        file_path = os.path.join(output_dir, filename)
        with open(file_path, 'wb') as file:
            file.write(response.content)
        convert_to_pdf(file_path, output_dir)  # 执行PDF转换
    else:
        raise Exception("Failed to download or convert file")

@csrf_exempt
@require_http_methods(['POST'])
def print_report_file(request):
    req_data = json.loads(request.body)
    form_inst_ids = req_data.get('form_inst_ids',[])
    form_uuid = "FORM-C1A327686C7A4FC68273017159DDE1A9PWVO"
    reports_pdf_paths=[]
    if len(form_inst_ids):
        temp_dir = tempfile.mkdtemp()
        for form_inst_id in form_inst_ids:
            yida_instance = yida_client.get_form_items_by_ids(form_uuid,form_inst_id,admin_user_id)
            form_data:dict = yida_instance[0].form_data
            report_file_url = json.loads(form_data["attachmentField_lwf41dza"])[0].get("downloadUrl")
            # 下载完整报告
            with requests.Session() as session:  # 使用 requests 库创建一个会话对象，用于发送 HTTP 请求。
                response = session.get(report_file_url)  # 发送 GET 请求以获取文件内容。
                if response.status_code == 200:
                    report_content = response.content
                    temp_report_path = os.path.join(temp_dir, f"{form_inst_id}.pdf")
                    print(f"完整报告文件已存入缓存文件：{temp_report_path}")
                    with open(temp_report_path, 'wb') as temp_file:
                        temp_file.write(report_content)
                    reports_pdf_paths.append(temp_report_path)
        
        out_path = os.path.join(temp_dir, "AllReports.pdf")
        merge_pdfs(reports_pdf_paths,out_path)                
        oss_pdf_key = f"yida-app/{company_name}/{form_uuid}/报告{uuid.uuid4()}.pdf"
        bucket.put_object_from_file(oss_pdf_key,out_path)
        out_url = f"https://api.zjcxjc.cn/api/v1/yida-app/common/download_file/{oss_pdf_key}"
        return ApiResponse.success(data=out_url,message='报告打印成功')
    return ApiResponse.fail('报告打印失败')

@csrf_exempt
@require_http_methods(["POST"])
def batch_print_yplzd(request):
    req_data = json.loads(request.body)
    form_inst_ids = req_data.get('form_inst_ids')
    form_uuid = "FORM-855DADF456844DFB97682B3B85C83212CRGP"
    model_id = 161
    table_data = []
    render_data = {
        "打印时间":datetime.now().timestamp(),
        "表格内容":table_data
    }
    for index,form_inst_id in enumerate(form_inst_ids):
        yida_instance = yida_client.get_form_items_by_ids(form_uuid,form_inst_id,admin_user_id)
        form_data:dict = yida_instance[0].form_data
        wtrq = datetime.fromtimestamp(form_data["dateField_lw4oxok2"]/1000).strftime("%Y-%m-%d")
        jcdm = "" #监测代码
        ypmc = form_data["textareaField_lvhpww36"]
        ypbh = form_data["textField_lvhpww3f"]
        slr = form_data["employeeField_lvuo2hz7"][0]
        jsr = "" #接收人
        jsrq = "" #接受日期
        ypcz = "" #样品处置
        bz = form_data["textField_lw6b30qv"] #备注
        table_data.append([index+1,wtrq,jcdm,ypmc,ypbh,slr,jsr,jsrq,ypcz,bz])
    XmCloudClient = get_xm_client(company_name)
    xm_client:XmCloudBaseClient = XmCloudClient()
    result_render = xm_client.render_model_xlsx(model_id,render_data)
    if result_render.get("code") == 200:
        res_data = result_render.get("data")
        result_url =xm_client.gen_detection_record_url(res_data.get("id"))
        if result_url.get("code") == 200:
            res = result_url.get("data")
            return ApiResponse.success(res.get("preview_url"))      

@csrf_exempt
@require_http_methods(["GET"])
def sign_name_to_full_report(request):
    form_inst_id = request.GET.get('formInstId')
    form_uuid = "FORM-C1A327686C7A4FC68273017159DDE1A9PWVO"
    model_id = request.GET.get('model_id')
    # 获取表单数据
    yida_instance = yida_client.get_form_items_by_ids(form_uuid, form_inst_id, admin_user_id)
    if not yida_instance:
        return ApiResponse.fail(message="未找到相关表单数据")
    
    form_data:dict = yida_instance[0].form_data
    
    #签名获取
    tester_signature_url_1 = form_data.get('digitalSignatureField_lwed3j4v')
    tester_signature_url_2 = ''
    reviewer_signature_url = form_data.get('digitalSignatureField_lwinoatx')
    approver_signature_url = form_data.get('digitalSignatureField_lwinoaty')
    sign_data = {"检测人签名1":tester_signature_url_1,"检测人签名2":tester_signature_url_2,
                 "审核人签名":reviewer_signature_url,"批准人签名":approver_signature_url}
    oss_key = form_data.get('textField_lwrvb5wq')
    pdf_info = {"oss_key":oss_key}
    sign_data_parms = {"sign_data":sign_data,"pdf_info":pdf_info}

    XmCloudClient = get_xm_client(company_name)
    xm_client:XmCloudBaseClient = XmCloudClient()
    result = xm_client.sign_to_pdf_file(model_id,sign_data_parms)
    if result.get("code") == 200:
        return ApiResponse.success(message='签名成功')
    return ApiResponse.fail('签名失败')


@csrf_exempt
@require_http_methods(["GET"])
def batch_print_jsd(request):
    formInstId = request.GET.get('formInstId')
    form_uuid = "FORM-01669FDF4C0B4FA4A04D0B72B50376A2TYMA"
    model_id = 159
    yida_instance = yida_client.get_form_items_by_ids(form_uuid,formInstId,admin_user_id)
    form_data_be:dict = yida_instance[0].form_data
    priced_info_str = form_data_be.get('associationFormField_lvkva1eh_id')
    form_inst_ids = []
    if priced_info_str:
        priced_info_list = json.loads(json.loads(priced_info_str))
        for priced_info in priced_info_list:
            form_inst_ids.append(priced_info.get('instanceId'))
        if form_inst_ids:
            table_data = []
            render_data = {
                "结算数据":table_data
            }

            for form_inst_id in form_inst_ids:
                yida_instance = yida_client.get_form_items_by_ids("FORM-9C48925B91404850BB1D00FC021A33C5RM1O",form_inst_id,admin_user_id)
                form_data:dict = yida_instance[0].form_data
                
                bg_info_str=form_data.get('associationFormField_lvw1b8w6_id')
                bg_info_detail=yida_client.get_associated_form_data(bg_info_str, admin_user_id)
                report_date_timestamp = bg_info_detail.get('dateField_lvhpww4i') #报告日期的毫秒时间戳
                if report_date_timestamp is not None:
                    report_date = datetime.fromtimestamp(report_date_timestamp / 1000).strftime('%Y年%m月%d日')
                else:
                    report_date = ''  # 报告日期

                wt_info_str = form_data.get('associationFormField_lvvrg0yz_id')
                wt_info_detail = yida_client.get_associated_form_data(wt_info_str, admin_user_id)
                project_name = wt_info_detail.get('textField_lvhw5i6u') #工程名称
                gc_info_str = wt_info_detail.get('associationFormField_lvhvyzpu_id') #关联工程
                gc_info_detail = yida_client.get_associated_form_data(gc_info_str, admin_user_id)
                entrust_unit = gc_info_detail.get('textField_lvhea612') #委托单位

                test_items = []  # 使用列表来收集参数
                test_project = wt_info_detail.get('selectField_lvhhb44k')  #检测项目
                if(wt_info_detail.get('radioField_lw8xidqm')=='常规'):
                    test_parms_table = wt_info_detail.get('tableField_lvituc5q')
                    unit = test_parms_table[0].get('selectField_lvj4hiij')  # 单位
            
                    for test_parm in test_parms_table:
                        item = test_parm.get('selectField_lwik49tr')
                        if item:  
                            test_items.append(item)
            
                    test_items = '、'.join(test_items)

                count =1 #数量
                report_info_str = form_data.get('associationFormField_lvw1b8w6_id')
                report_info_detail = yida_client.get_associated_form_data(report_info_str, admin_user_id)
                report_number = report_info_detail.get('textField_lvksipo5') #报告编号
                unit_price = float(wt_info_detail.get('numberField_lvkpm5tz')) #单价
                total_price = unit_price  #检测费
                table_data.append([report_date,entrust_unit,project_name,test_project,test_items,unit,count,report_number,unit_price,total_price])
            
            XmCloudClient = get_xm_client(company_name)
            xm_client:XmCloudBaseClient = XmCloudClient()
            result_render = xm_client.render_model_xlsx(model_id,render_data)
            if result_render.get("code") == 200:
                res_data = result_render.get("data")
                result_url =xm_client.gen_detection_record_url(res_data.get("id"))
                if result_url.get("code") == 200:
                    res = result_url.get("data")
                    yida_client.update_form_data_by_id(form_uuid, admin_user_id, formInstId, {
                        "attachmentField_lwsvad6v": [{
                            "downloadUrl": res.get("download_url"),
                            "name": "电子结算单.pdf",
                            "previewUrl": res.get("preview_url"),
                            "url": res.get("download_url"),
                            "ext": "pdf"
                        }]
                    })
                    return ApiResponse.success(res.get("preview_url"))
                

# 使用宜搭数据在平台创建工程并生成二维码去创建委托
@csrf_exempt
@require_http_methods(["GET"])
def get_uuid_QRcode_by_project(request):
    formInstId = request.GET.get('formInstId')
    form_uuid = 'FORM-B973E0A2EA7C452F9D3B7077821CE7C6TVSO'
    yida_instance = yida_client.get_form_items_by_ids(form_uuid, formInstId, admin_user_id)
    
    body = {
        "project_number": yida_instance[0].form_data["textField_m023zgi3"],  # 项目编号
        "registration_date": yida_instance[0].form_data["dateField_lzrzlfjq"],  # 登记日期
        "project_name": yida_instance[0].form_data["textField_lzrzlfjr"],  # 项目名称
        "project_address": yida_instance[0].form_data["textareaField_lzxvw0ez"],  # 项目地址
        "callback_url": "haorui"
    }
    XmCloudClient = get_xm_client('haorui')
    xm_client:XmCloudBaseClient = XmCloudClient()
    response = xm_client.create_project(body)
    
    if response.get('code') == 200:
        project_token = response.get('data').get('project_token')
        print('project_token--->',project_token)
        qr_url = f'http://report.zjxmyq.cn/commission/create?uuid={project_token}'
        # Generate QR code
        qr = qrcode.QRCode(
            version=1,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=10,
            border=4,
        )
        qr.add_data(qr_url)
        qr.make(fit=True)
        img = qr.make_image(fill='black', back_color='white')
        # Convert image to base64
        buffered = BytesIO()
        img.save(buffered, format="PNG")
        img_base64 = base64.b64encode(buffered.getvalue()).decode('utf-8')
        
        # Pass base64 image to template
        context = {
            'qrcode': f"data:image/png;base64,{img_base64}",
            'url': qr_url,
            "company_name":"浙江浩瑞工程检测有限公司"
        }
        return render(request, 'qrcode_by_project.html', context)
    else:
        return ApiResponse.fail('失败')

    
# 在宜搭中创建委托   
@csrf_exempt
@require_http_methods(["POST"])
def create_commission_yida(request):
    req_data = json.loads(request.body)
    commision_info = req_data.get('commision_info')
    # print('commision_info--->',commision_info)
    # yida_data = {}
    # 工程数据
    project_data = yida_client.get_form_data_by_search_field(
        'FORM-B973E0A2EA7C452F9D3B7077821CE7C6TVSO',
        admin_user_id,
        {
            "textField_lzrzlfjr":req_data.get("project_name")
        }
    )
    xm_client = XmCloudClient()
    print('1111--->',req_data.get("detection_project_id"))
    exam_data = xm_client.get_xm_exam_item_detail(req_data.get("detection_project_id"))
    print('exam_data--->',exam_data)
    if exam_data.get('code') == 200:
        contracts_code = exam_data.get('data').get('commision_code')
        print('commision_code--->', contracts_code)
        match_field_data = {
          "textField_m0dhjgye": contracts_code,
        }
        # 流水号
        serial_number = gen_serial_number(
            'FORM-855DADF456844DFB97682B3B85C83212CRGP',
            match_field_data,
            'numberField_lzxv9z4i'
        )
        print('流水号--->',serial_number)
        contracts_report = contracts_code +'-'+ str(datetime.now().year) +'-' + f"{serial_number:05}"
        print('委托编号--->',contracts_report)
    # return
    
    # 资质类别
    label = req_data.get("qualification_name")
    print('资质类别--->', label)
    yida_client.create_form_data(
        'FORM-855DADF456844DFB97682B3B85C83212CRGP',
        admin_user_id,
        {
            "associationFormField_lzs0x0am":[
              {
                "appType": 'APP_LSBE7XYKW28JNYBTQLC0', 
                "formType": 'receipt',
                "formUuid": 'FORM-B973E0A2EA7C452F9D3B7077821CE7C6TVSO',
                "instanceId": project_data[0].form_instance_id,
                "title": project_data[0].form_data["textField_lzrzlfjr"],
              },  
            ],
            "selectField_lzw4hk74": label,  #资质类别
            "selectField_lzw4hk6z": req_data.get("exam_name")[0],  #检测大类
            # detection_project_id
            "selectField_m0kl14bq":req_data.get("detection_project_id"),  #检测项目
            # "selectField_m0kl14bq": req_data.get("exam_name")[1],  #检测项目
            "textField_m0dhjgye": contracts_code,  #委托代码
            "numberField_lzxv9z4i": serial_number,  #委托流水号
            "textField_lzs0x0b9": contracts_report,  #委托编号
            "employeeField_lzs0x0b4": ["300208014636253254"],  #编制人  
            "radioField_m025klsq": "见证取样",
        }
    )
    # 查询委托数据
    commission_data = yida_client.get_form_data_by_search_field(
        'FORM-855DADF456844DFB97682B3B85C83212CRGP',
        admin_user_id,
        {
            "textField_lzs0x0b9":contracts_report
        }
    )
    # print('commission_data--->',commission_data[0].form_instance_id)
    for index, sample in enumerate(commision_info):
        # 检测参数列表
        tableDataList = []
        for item in sample['tableData']:
            tableData = {}
            tableData["textField_m0kma0fo"] = item["name"]  # 参数名称
            tableData["textField_m0kma0fn"] = item["id"]  # uuid
            tableDataList.append(tableData)
        print('tableDataList--->',tableDataList)
        # print('------>',sample['sampleParameters'].get("production_date"))
        # time_str = sample['sampleParameters'].get("production_date")
        # # 使用 isoparse 自动解析时间字符串
        # production_date = parser.isoparse(time_str)
        # print("production_date---->",production_date)
        # # 如果需要将其转化为毫秒级别的时间戳
        # timestamp_ms = int(production_date.timestamp() * 1000)
        # production_date_ms = int(production_date.timestamp() * 1000)
        yida_client.create_form_data(
            'FORM-86B7C5FF74F646FABCC38B232127CBE5P73M',
            admin_user_id,
            {
                "associationFormField_lzuvjinv":[
                  {
                    "appType": 'APP_LSBE7XYKW28JNYBTQLC0', 
                    "formType": 'receipt',
                    "formUuid": 'FORM-855DADF456844DFB97682B3B85C83212CRGP',
                    "instanceId": commission_data[0].form_instance_id,
                    "title": commission_data[0].form_data["textField_lzuvzaex"],
                  },  
                ],
                "tableField_lzuvjio2": tableDataList,  #检测参数
                "textField_lzwdkwlk":contracts_report,  #委托编号
                "serialNumberField_lzuvjiny":contracts_report+'-'+str(index+1),  #样品编号
                "selectField_m0kma0fg":label,  #资质类别
                "selectField_m0kma0fh":req_data.get("exam_name")[0],  #检测大类
                "selectField_m0kma0fi":req_data.get("exam_name")[1],  #检测项目
                "selectField_m0kma0fj":sample['sampleParameters'].get("sample_spec"),  #规格
                "textField_m0kma0fq":sample['sampleParameters'].get("sample_name"),  #样品名称
                "textField_m0kma0fr":sample['sampleParameters'].get("sample_status"),  #样品状态
                # "dateField_m0kma0fv":production_date_ms,  #生产日期
                "textField_m0kma0fu":sample['sampleParameters'].get("production_manufacturer"),  #生产厂家
                "numberField_m0kma0g6":sample['sampleParameters'].get("sample_count"),  #样品数量
                "textField_m0kma0gn":sample['sampleParameters'].get("pledge_number"),  #质保单号
                "textField_m0kma0g8":sample['sampleParameters'].get("position"),  #结构部位
                "numberField_m0kma0gf":sample['sampleParameters'].get("representative_count"),  #代表数量
                "textField_m0kma0ge":sample['sampleParameters'].get("engineering_site"),  #工程部位
            }
        )
    return ApiResponse.success(data=contracts_report, message='成功')

def gen_serial_number(form_uuid,match_field_data,sn_field):
    try:
        if isinstance(match_field_data,list):
            match_field_data = match_field_data + [{"key":sn_field,"value":"","type":"DOUBLE","operator":"is_not","componentName":"NumberField"}]
        result = yida_client.get_form_data_by_search_field(form_uuid=form_uuid,
                                                  userId=admin_user_id,
                                                  search_field=match_field_data,
                                                  page_size=5,
                                                  dynamic_order={sn_field:"-"})
        if result:
            serial_number = result[0].form_data.get(sn_field,0)+1
            return serial_number
        elif len(result) == 0:
            return 1
    except Exception as err:
        return 0
    
@csrf_exempt
@require_http_methods(["GET"])
def calc_total_amount(request):
    commission_id = request.GET.get("commission_id")
    results,total = yida_client.get_all_form_data_by_search_field("FORM-86B7C5FF74F646FABCC38B232127CBE5P73M",
                                                  admin_user_id,
                                                  search_field=[
                                                        {
                                                            "type": "TEXT",
                                                            "operator": "eq",
                                                            "componentName": "TextField",
                                                            "key": "textField_lzj6tn3n",
                                                            "value": commission_id
                                                        }
                                                    ])
    total_amount = sum(item.form_data['numberField_lzgnuame'] for item in results if 'numberField_lzgnuame' in item.form_data)
    
    try:
        response = yida_client.update_form_data_by_field(
            "FORM-855DADF456844DFB97682B3B85C83212CRGP",
            admin_user_id,
            [{
                "type": "TEXT",
                "operator": "eq",
                "componentName": "TextField",
                "key": "textField_lvhpww3e",
                "value": commission_id
            }],
            {"numberField_lvkpm5tz": total_amount }  
        )
        if response == "success":
            return ApiResponse.success(response)
        else:
            return ApiResponse.fail(response,400)
    except Exception as e:
        print(e)
        return ApiResponse.fail("更新失败",400)


@csrf_exempt
@require_http_methods(["GET"])
def create_report(request):
    report_inst_id = request.GET.get("report_inst_id")
    report_result = yida_client.get_form_items_by_ids(form_uuid="FORM-6BF4AA8093E44BF7A7C6FCB1BA056CC2UR1A",form_inst_id=report_inst_id,userId=admin_user_id)
    print('report_result--->',report_result)
    report_form:dict = report_result[0].form_data
    wt_inst = json.loads(json.loads(report_form.get("associationFormField_lzw5dy60_id")))
    print(wt_inst[0].get('formUuid'),wt_inst[0].get("instanceId"))
    commission_result = yida_client.get_form_items_by_ids(wt_inst[0].get('formUuid'),wt_inst[0].get("instanceId"),admin_user_id)
    commission_form = commission_result[0].form_data
    gc_inst = json.loads(json.loads(commission_form.get("associationFormField_lzs0x0am_id")))
    project_result = yida_client.get_form_items_by_ids(gc_inst[0].get('formUuid'),gc_inst[0].get("instanceId"),admin_user_id)
    project_form = project_result[0].form_data
    # detection_project_inst = json.loads(json.loads(commission_form.get("associationFormField_lzs0x0b3_id")))
    # detection_project_result = yida_client.get_form_items_by_ids(detection_project_inst[0].get('formUuid'),detection_project_inst[0].get("instanceId"),admin_user_id)
    # detection_project_form = detection_project_result[0].form_data
    xm_client = XmCloudClient()
    print('编号-->',commission_form.get("selectField_m0kl14bq_id"))
    params_list = xm_client.get_xm_exam_item_detail(commission_form.get("selectField_m0kl14bq_id"))
    print('params_list--->',params_list.get("data"))
    render_data = {        
        "送检日期":None,  #时间
        "检测仪器":"",
        "工程名称": project_form.get("textField_lzrzlfjr"),
        "检测项目": params_list.get("data").get('name'),
        "样品状态":"",
        "规格型号":"",
        "批号":"",
        "代表数量":"",  #数字
        "见证单位":"",
        "生产日期":None,  #时间
        "报告编号":commission_form.get("textField_lzs0x0b9"),
        "样品数量":"",
        "委托人": commission_form.get("textField_lzxv9z4b"),
        "判定依据":"",
        "见证人":"",
        "施工单位":project_form.get("textField_lzrzlfk8"),
        "报告日期":None,
        "备注":"",
        "质保单号":"",
        "委托单位": commission_form.get("textField_lzs0x0ba"),
        "检测结论":"",
        "工程部位":"",
        "送样日期":None,
        "样品名称":"",
        "生产单位":"",
    }    
    create_report_result = xm_client.create_special_report_record(model_ids=params_list.get("data").get("report_model"),
                                           name=commission_form.get("textField_lzs0x0b9"),
                                           pub_render_data=render_data)
    if create_report_result.get("code") == 200:
        return ApiResponse.success(create_report_result.get("data"))
    else:
        return ApiResponse.fail(create_report_result.get("message"))
